/**
 * 获取url参数
 */
const getToken = () => {
//   var token = this.$route.query.token;
//   if (token) {
//     sessionStorage.setItem("token", token);
//   } else {
//     token = sessionStorage.getItem("token");
//   }
//   console.log(token);
//   return token;
}


/**
 * 判断浏览器内核
 */
const core = () => {
  if (navigator.userAgent.match(/MicroMessenger/gi)) {
    return "wx";
  } else if (navigator.userAgent.match(/\sQQ/i)) {
    return "QQ";
  } else if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/Adr/i) || navigator.userAgent.match(/android/i) || navigator.userAgent.match(/adr/i)) {
    return "android";
  } else if (navigator.userAgent.match(/Mac OS X/i)) {
    return "iOS";
  } else {
    return "other";
  }
}


/**
 *  获取时间和年月日
 */
const date = new Date(); // 获取当前时间
const year = date.getFullYear(); // 获取当前年
const month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1); // 获取当前月
const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); // 获取当前日
const first_date = year + '/' + month + '/01'; // 获取当前月第一天
const daydate = new Date(year, month, 0); // 获取当前月最后一天凌晨时间
const last_date = daydate.getDate(); // 获取当前月最后一天日期
const today = year + '/' + month + '/' + day; // 获取当前年月日
// 当前年近5年的时间选择
var dataSelect = [];
for (var a = 0; a < 5; a++) {
  for (var b = 0; b < 12; b++) {
    var yearSplit = year - a;
    if (a == 0 && month - b > 0) {
      var monthSplit = month - b;
    } else if (a > 0) {
      var monthSplit = 12 - b;
    } else {
      break;
    }
    var v = yearSplit + "年" + monthSplit + "月";
    dataSelect.push(v);
  }
}
// 获取系统前一周的时间
var weekDate = new Date(date - 7 * 24 * 3600 * 1000);
var weekY = weekDate.getFullYear();
var weekM = weekDate.getMonth() + 1;
var weekD = weekDate.getDate();
var oneWeekDate = weekY + '-' + weekM + '-' + weekD;
//获取系统前一个月的时间
date.setMonth(date.getMonth() - 1);
var monthY = year;
var monthM = month - 1;
var monthD = day;
var oneMonthData = monthY + '-' + monthM + '-' + monthD;
// 转换时间戳
const timestamp = (date, timedate) => {
  var datetime = (date + timedate).replace(/-/g, '/');
  return new Date(datetime).getTime() / 1000; // (年月日,时分秒)
}
//秒 转化成 时分秒
const secondToDate = (result) => {
  var h = Math.floor(result / 3600);
  var m = Math.floor((result / 60 % 60));
  var s = Math.floor((result % 60));
  return result = h + "时" + m + "分" + s + "秒";
}
// 时间戳转换日期
const getLocalTime = (nS) => {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
}


/**
 * 压缩图片
 */
// 用于压缩图片的canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
// 瓦片canvas
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
var maxsize = 100 * 1024; //设置如果图片大小小于100kb，则直接上传
var blobObject = {}; //blob数组，用来绑定区别input的id
// 使用canvas对大图片进行压缩
const canvasCompress = (img) => {
  var initSize = img.src.length;
  var width = img.width;
  var height = img.height;

  //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
  var ratio;
  if ((ratio = width * height / 4000000) > 1) {
    ratio = Math.sqrt(ratio);
    width /= ratio;
    height /= ratio;
  } else {
    ratio = 1;
  }

  canvas.width = width;
  canvas.height = height;

  //        铺底色
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  //如果图片像素大于100万则使用瓦片绘制
  var count;
  if ((count = width * height / 1000000) > 1) {
    count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片

    //            计算每块瓦片的宽和高
    var nw = ~~(width / count);
    var nh = ~~(height / count);

    tCanvas.width = nw;
    tCanvas.height = nh;

    for (var i = 0; i < count; i++) {
      for (var j = 0; j < count; j++) {
        tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);

        ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
      }
    }
  } else {
    ctx.drawImage(img, 0, 0, width, height);
  }

  // 进行最小压缩
  var ndata = canvas.toDataURL('image/jpeg', 0.1);

  console.log('压缩前：' + initSize);
  console.log('压缩后：' + ndata.length);
  console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");

  tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;

  return ndata;
}
// 塞数组，将base64的图片转成二进制对象，再塞进到blob数组里面。
const insertion = (basestr, type, id) => {
  var text = window.atob(basestr.split(",")[1]);
  var buffer = new Uint8Array(text.length);

  for (var i = 0; i < text.length; i++) {
    buffer[i] = text.charCodeAt(i);
  }

  // 塞进数组
  blobObject[id] = getBlob([buffer], type);
}
// 获取blob对象的兼容性写法
const getBlob = (buffer, format) => {
  try {
    return new Blob(buffer, {
      type: format
    });
  } catch (e) {
    var bb = new(window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
    buffer.forEach(function (buf) {
      bb.append(buf);
    });
    return bb.getBlob(format);
  }
}
// 开始获取流，实例化一个FileReader，以base64格式读取上传的文件数据，files是文件，id是input 数组id
const compressValue = (files, id) => {
  if (!files.length) return;
  var file = files[0];
  if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;

  var reader = new FileReader();
  reader.onload = function () {
    var result = this.result;
    var img = new Image();
    img.src = result;

    //设置图片大小，则直接上传
    if (result.length <= maxsize) {
      img = null;
      insertion(result, file.type, id);
      return;
    }

    // 图片加载完毕之后进行压缩，然后上传
    if (img.complete) {
      callback();
    } else {
      img.onload = callback;
    }

    function callback() {
      var data = canvasCompress(img);
      insertion(data, file.type, id);
      img = null;
    }
  };
  reader.readAsDataURL(file);
};


/**
 * formdata 补丁
 */
// formdata 补丁, 给不支持formdata上传blob的android机打补丁
const FormDataShim = () => {
  console.warn('using formdata shim');

  var o = this,
    parts = [],
    boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
    oldSend = XMLHttpRequest.prototype.send;

  this.append = function (name, value, filename) {
    parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');

    if (value instanceof Blob) {
      parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
      parts.push(value);
    } else {
      parts.push('\r\n\r\n' + value);
    }
    parts.push('\r\n');
  };

  // Override XHR send()
  XMLHttpRequest.prototype.send = function (val) {
    var fr, data, oXHR = this;

    if (val === o) {
      // Append the final boundary string
      parts.push('--' + boundary + '--\r\n');

      // Create the blob
      data = getBlob(parts);

      // Set up and read the blob into an array to be sent
      fr = new FileReader();
      fr.onload = function () {
        oldSend.call(oXHR, fr.result);
      };
      fr.onerror = function (err) {
        throw err;
      };
      fr.readAsArrayBuffer(data);

      // Set the multipart content type and boudary
      this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
      XMLHttpRequest.prototype.send = oldSend;
    } else {
      oldSend.call(this, val);
    }
  };
}
// 获取formdata
const getFormData = () => {
  var isNeedShim = ~navigator.userAgent.indexOf('Android') &&
    ~navigator.vendor.indexOf('Google') &&
    !~navigator.userAgent.indexOf('Chrome') &&
    navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;

  return isNeedShim ? new FormDataShim() : new FormData()
}


/**
 * 正则判断
 */

// 判断是否为纯数字
const checkNumber = (num) => {
  var reg = /^[0-9]*$/;
  if (reg.test(num)) {
    // console.log("setting判断是否为纯数字", "true");
    return true;
  }
  // console.log("setting判断是否为纯数字:", "false");
  return false;
}


/**
 * 触发失去所有input焦点
 */
const removeFocus = () => {
  $("input").blur();
}


/**
 * 公告滚动加载
 */
const notice = () => {
  var data = '又是一年百花竞放，又是一载春华秋实，蜂窝互娱愿新老朋友新的一年心想事成。'; // 数据
  var doc = document.querySelector('.notice .box');
  doc.innerHTML = '<p class="text1">' + data + '</p>' + '<p class="text2">' + data + '</p>'; // 插入数据
  var width = document.querySelector('.notice .box p').offsetWidth; // 一份数据的宽度
  // document.querySelector('.notice .box').style.width = (width * 2) + 'px';
  var text1 = document.querySelector(".text1");
  var text2 = document.querySelector(".text2");
  var x = 0;
  var scrollleft = function () {
    text1.style.left = x + 'px';
    text2.style.left = (x + width) + 'px';
    x--;
    if ((x + width) == 0) {
      x = 0;
    }
  };
  setInterval(scrollleft, 20);
}

export default {
  getToken,
  core,
  first_date,
  today,
  dataSelect,
  oneWeekDate,
  oneMonthData,
  timestamp,
  secondToDate,
  getLocalTime,
  compressValue,
  getFormData,
  checkNumber,
  removeFocus,
  notice
};
